package com.pro01.backend.service;

import com.pro01.backend.mapper.NotificationMapper;
import com.pro01.backend.mapper.UserMapper;
import com.pro01.backend.pojo.Notification;
import com.pro01.backend.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminNotificationService {

    @Autowired
    private NotificationMapper notificationMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 管理员发送系统通知
     */
    public void sendSystemNotification(String content, String link) {
        List<Long> userIds = userMapper.getAllUserIds();
        for (Long userId : userIds) {
            Notification notification = new Notification();
            notification.setUserId(userId);
            notification.setSenderId(null); // 系统发送，无sender
            notification.setType("SYSTEM_NOTICE");
            notification.setContent(content);
            notification.setLink(link);
            notification.setStatus("UNREAD");

            notificationMapper.insertNotification(notification);
        }
    }

    /**
     * 管理员查看所有系统通知
     */
    public PageResult<Notification> getSystemNotifications(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<Notification> records = notificationMapper.selectGroupedSystemNotifications(offset, pageSize);
        int total = notificationMapper.countGroupedSystemNotifications();
        return new PageResult<>(total, records);
    }

    /**
     * 管理员删除系统通知
     */
    public void deleteSystemNotification(String content, String link) {
        int result = notificationMapper.deleteSystemNotification(content, link);
        if (result == 0) {
            throw new RuntimeException("删除失败，找不到对应的系统通知");
        }
    }


}
